﻿using System;
using System.Collections.Generic;
using System.Linq;
using MetroIoc;

namespace metroioc.Container
{
    public class LifetimeScope
    {
        IDictionary<Tuple<Type, string>, TypeResolver> RegistrationCollection { get; set; }

        internal LifetimeScope()
        {
            RegistrationCollection = new Dictionary<Tuple<Type, string>, TypeResolver>();
        }

        public Type DeriveType(string key)
        {
            return GetTypeFromContainer(key, RegistrationCollection);
        }

        internal IEnumerable<KeyValuePair<Tuple<Type, string>, TypeResolver>> Registrations
        {
            get { return RegistrationCollection; }
        } 

        internal static Type GetTypeFromContainer(string key, IDictionary<Tuple<Type, string>, TypeResolver> resolvers)
        {
            var tuple = resolvers
                .Keys
                .FirstOrDefault(t => t.Item2 == key);

            return (tuple == null)
                        ? null
                        : tuple.Item1;
        }

        internal bool TryGetValue(Tuple<Type, string> key, out TypeResolver value)
        {
            return RegistrationCollection.TryGetValue(key, out value);
        }

        internal TypeResolver Get(Tuple<Type, string> key)
        {
            return RegistrationCollection[key];
        }

        internal void Add(Tuple<Type, string> key, TypeResolver value)
        {
            RegistrationCollection.Add(key, value);
        }

        internal void Set(Type type, string key, TypeResolver value)
        {
            RegistrationCollection[new Tuple<Type, string>(type, key)] = value;
        }
    }
}
